﻿using System;
using System.Text;

/* Write a program to check if in a given expression the brackets are put correctly.
Example of correct expression: ((a+b)/5-d).
Example of incorrect expression: )(a+b)). */

class Brackets
{
    static void Main()
    {
        Console.Write("Enter an expression: ");
        string expression = Console.ReadLine();

        if (CheckBrackets(expression) == 0)
        {
            Console.WriteLine("The brackects in this expression are corerct!");
        }
        else
        {
            Console.WriteLine("The brackects in this expression are not corerct!");
        }
    }

    static int CheckBrackets(string expression)
    {
        StringBuilder brackets = new StringBuilder();

        for (int i = 0; i < expression.Length; i++)
        {
            char symbol = expression[i];
            int length = brackets.Length;

            if (symbol == '(' || symbol == ')')
            {
                if (length > 0)
                {
                    if (symbol == ')')
                    {
                        if (brackets[length - 1] == '(')
                        {
                            brackets.Remove(length - 1, 1);
                        }
                        else
                        {
                            return -1;
                        }
                    }
                    else
                    {
                        brackets.Append(symbol);
                    }
                }
                else
                {
                    brackets.Append(symbol);
                }
            }
        }

        return 0;
    }
}